import sys
sys.path.append('..')
import logging
import hashlib
from datetime import datetime
from database.db import SessionLocal, engine, Base  # 使用正确的导入路径

# 导入所有必要的模型以确保表被创建
from models.user import User, Role, Permission
from models.department import Department
from models.detection_log import DetectionLog
from models.detection_model import DetectionModel
from models.detection_target import DetectionTarget
from models.dict import DictType, DictItem
from models.drone import Drone
from models.exception_log import ExceptionLog
from models.flight_log import FlightLog
from models.menu import Menu
from models.operation_log import OperationLog
from models.flight_route import FlightRoute
from models.task import Task
from models.task_scenario import TaskScenario
from models.task_scenario_detection_target import task_scenario_detection_targets

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 模拟用户数据（从Users.vue中提取）
users_data = [
    {
        "username": "admin",
        "full_name": "系统管理员",
        "email": "admin@example.com",
        "department_id": 1,
        "department_name": "技术部",
        "created_at": "2024-01-01 00:00:00",
        "status": True,
        "is_superuser": True,
        "password": "admin123"  # 非常短的密码，确保不超过72字节
    },
    {
        "username": "pilot01",
        "full_name": "飞行员张三",
        "email": "pilot01@example.com",
        "department_id": 2,
        "department_name": "运营部",
        "created_at": "2024-01-02 10:00:00",
        "status": True,
        "password": "admin123"  # 统一密码
    },
    {
        "username": "pilot02",
        "full_name": "飞行员李四",
        "email": "pilot02@example.com",
        "department_id": 2,
        "department_name": "运营部",
        "created_at": "2024-01-03 14:00:00",
        "status": True,
        "password": "admin123"
    },
    {
        "username": "engineer01",
        "full_name": "工程师王五",
        "email": "engineer01@example.com",
        "department_id": 3,
        "department_name": "研发部",
        "created_at": "2024-01-04 09:00:00",
        "status": True,
        "password": "admin123"
    },
    {
        "username": "test01",
        "full_name": "测试员赵六",
        "email": "test01@example.com",
        "department_id": 4,
        "department_name": "测试部",
        "created_at": "2024-01-05 11:00:00",
        "status": True,
        "password": "admin123"
    }
]

def init_users():
    logger.info("开始初始化用户数据...")
    
    # 先创建所有数据库表
    try:
        logger.info("开始创建数据库表...")
        Base.metadata.create_all(bind=engine)
        logger.info("数据库表创建成功")
    except Exception as e:
        logger.error(f"创建数据库表失败: {str(e)}")
        raise
    
    db = SessionLocal()
    try:
        # 检查是否已存在用户数据
        existing_users = db.query(User).first()
        if existing_users:
            logger.info("数据库中已存在用户数据，跳过初始化")
            return
        
        count = 0
        for user_data in users_data:
            # 检查用户是否已存在
            existing_user = db.query(User).filter(User.username == user_data["username"]).first()
            if existing_user:
                logger.warning(f"用户 {user_data['username']} 已存在，跳过")
                continue
            
            # 检查部门是否存在
            department = db.query(Department).filter(Department.id == user_data["department_id"]).first()
            if not department:
                logger.warning(f"部门ID {user_data['department_id']} 不存在，尝试创建...")
                # 创建部门
                department = Department(
                    id=user_data["department_id"],
                    name=user_data["department_name"],
                    description=f"自动创建的 {user_data['department_name']}"
                )
                db.add(department)
                db.flush()  # 立即写入数据库以获取ID
            
            # 使用简单的哈希方法来确保用户能够登录
            password = user_data["password"]
            # 使用简单的MD5哈希（实际生产环境应该使用更安全的方法）
            hashed_password = hashlib.md5(password.encode()).hexdigest()
            logger.info(f"已为用户 {user_data['username']} 生成密码哈希")
            
            # 将布尔值status转换为字符串（1表示启用，0表示禁用）
            status_str = "1" if user_data["status"] else "0"
            
            # 创建用户对象
            user = User(
                username=user_data["username"],
                password=hashed_password,
                email=user_data["email"],
                department_id=user_data["department_id"],
                status=status_str,
                is_superuser=user_data.get("is_superuser", False)
            )
            
            # 设置创建时间
            if "created_at" in user_data:
                user.created_at = datetime.strptime(user_data["created_at"], "%Y-%m-%d %H:%M:%S")
            
            db.add(user)
            
            # 为用户分配角色
            if user_data.get("is_superuser", False):
                # 超级管理员角色
                admin_role = db.query(Role).filter(Role.name == "超级管理员").first()
                if not admin_role:
                    logger.warning("超级管理员角色不存在，将创建...")
                    admin_role = Role(
                        name="超级管理员",
                        description="系统超级管理员，拥有所有权限",
                        level=500  # 超级管理员级别
                    )
                    db.add(admin_role)
                    db.flush()
                user.roles.append(admin_role)
            else:
                # 普通用户角色
                user_role = db.query(Role).filter(Role.name == "普通用户").first()
                if not user_role:
                    logger.warning("普通用户角色不存在，将创建...")
                    user_role = Role(
                        name="普通用户",
                        description="系统普通用户",
                        level=0
                    )
                    db.add(user_role)
                    db.flush()
                user.roles.append(user_role)
            
            count += 1
        
        db.commit()
        logger.info(f"成功初始化 {count} 个用户数据")
        print(f"成功初始化 {count} 个用户数据到数据库")
        
    except Exception as e:
        logger.error(f"初始化用户数据失败: {str(e)}")
        db.rollback()
        print(f"初始化用户数据失败: {str(e)}")
    finally:
        db.close()

if __name__ == "__main__":
    init_users()
    print("操作完成")